package com.vito.oa.act.print;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class ConvertHtml {
	private static final String FILE_TEMPLATE = Configuration.class.getClassLoader().getResource("/").getPath()+"conf/actPrintTemplate.ftl";
	private static final String FILE_OUTPUT = Configuration.class.getClassLoader().getResource("/").getPath()+"temp/out_put.html";
	/**
     * 把模板读入到String中，然后根据String构造FreeMarker模板
     */
    public static synchronized void createHtmlFromString(Object info) {
        BufferedInputStream in = null;
        OutputStreamWriter out = null;
        try {
            //模板文件
            File file = new File(FILE_TEMPLATE);
            //构造输入流
            in = new BufferedInputStream(new FileInputStream(file));
            int len;
            byte[] bytes = new byte[1024];
            //模板内容
            StringBuilder content = new StringBuilder();
            while((len = in.read(bytes)) != -1) {
                content.append(new String(bytes, 0, len, "utf-8"));
            }
            
            //构造Configuration
            Configuration configuration = new Configuration();
            //构造StringTemplateLoader
            StringTemplateLoader loader = new StringTemplateLoader();
            //添加String模板
            loader.putTemplate("test", content.toString());
            //把StringTemplateLoader添加到Configuration中
            configuration.setTemplateLoader(loader);
            
            //获取模板
            Template template = configuration.getTemplate("test");
            //构造输出路
            File outfile = new File(FILE_OUTPUT);
            outfile.getParentFile().mkdirs();
            out = new OutputStreamWriter(new FileOutputStream(outfile),"UTF-8");
            //生成HTML
            template.process(info, out);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            if(null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
    }
}
